<!-- 录像下载 -->
<template>
  <div>
    <Modal v-model="modal.show"  :loading="modal.loading" :title="modal.title"  :mask-closable="false" :footer-hide=true width="60" :closable="false">
      <row>
        <Col span="18">
          <Progress :percent="percent"></Progress>

        </Col>
        <Col span="6">
          <Button size="small" v-if="percent < 100" title="点击下载可将以缓存部分下载到本地" @click="download()">停止缓存并下载</Button>
          <Button size="small" v-if="downloadFile" title="点击下载" @click="downloadFileClientEvent()">点击下载 </Button>
        </Col>
      </row>
      <Row>
        <Col span="24"><div style="display: flex;justify-content: center">
            <Button type="primary" @click="close">关闭</Button>
          </div>
        </Col>
      </Row>
    </Modal>
  </div>
</template>
<script>
import GbRecord from "@/api/GbRecord"
import {apiResult} from "@/libs/util";
export default {
  name:"RecordDownload",
  data(){
    return{
      api: new GbRecord(),
      modal:{
        show:false,
        title: "录像下载...",
        loading: false
      },
      percent:0,
      downloadFile: null,
      streamInfo:null,
      deviceData:null,
      stream:null,
      timer:null,
      getProgressRun: false,
      getProgressForFileRun: false,
      mediaServerId:null,
      taskId:null
    }
  },
  methods:{
    openDialog: function (deviceData, app, stream, mediaServerId) {
      this.deviceData = deviceData;
      this.app = app;
      this.stream = stream;
      this.mediaServerId = mediaServerId;
      this.modal.show = true;
      this.getProgressRun = true;
      this.percent = 0.0;
      this.getProgressTimer();
    },
    getProgressTimer: function (){
      if (!this.getProgressRun) {
        return;
      }
      if (this.percent == 100 ) {
        this.getFileDownload();
        return;
      }
      setTimeout( ()=>{
        if (!this.modal.show) return;
        this.getProgress(this.getProgressTimer())
      }, 5000)
    },

    getProgress: function (callback){
      const param = {
        deviceCode:this.deviceData.arrt.deviceCode,
        channelCode: this.deviceData.arrt.channelCode,
        stream: this.stream,
      }
      this.api.downloadTaskProgress(JSON.stringify(param)).then(res=>{
          apiResult(res.data,false,result=>{
            this.streamInfo = result.data;
            if (parseFloat(res.data.progress) == 1) {
              this.percent = 100;
            }else {
              this.percent = (parseFloat(result.data.progress)*100).toFixed(1);
            }
            if (callback)callback();
          },err=>{
            this.close();
          })
      }).catch((e) =>{
        console.log(e)
      });
/*
      this.$axios({
        method: 'get',
        url: `/api/gb_record/download/progress/${this.deviceId}/${this.channelId}/${this.stream}`
      }).then((res)=> {
        console.log(res)
        if (res.data.code === 0) {
          this.streamInfo = res.data.data;
          if (parseFloat(res.data.progress) == 1) {
            this.percentage = 100;
          }else {
            this.percentage = (parseFloat(res.data.data.progress)*100).toFixed(1);
          }
          if (callback)callback();
        }else {
          this.$message({
            showClose: true,
            message: res.data.msg,
            type: "error",
          });
          this.close();
        }

      }).catch((e) =>{
        console.log(e)
      });*/
    },

    close(){
      if (this.streamInfo.progress < 1) {
        this.stopDownloadRecord();
      }

      if (this.timer !== null) {
        window.clearTimeout(this.timer);
        this.timer = null;
      }
      this.modal.show=false;
      this.getProgressRun = false;
      this.getProgressForFileRun = false;
    },
    download: function (){
      this.getProgressRun = false;
      if (this.streamInfo != null ) {
        if (this.streamInfo.progress < 1) {
          // 发送停止缓存
          this.stopDownloadRecord((res)=>{
            this.getFileDownload()
          })
        }else {
          this.getFileDownload()
        }
      }
    },
    stopDownloadRecord: function (callback) {
      const param = {
        deviceCode:this.deviceData.arrt.deviceCode,channelCode:this.deviceData.arrt.channelCode,stream:this.stream
      }
      this.api.downloadStop(JSON.stringify(param)).then(res=>{
        if (callback) callback(res)
      })
      /*this.$axios({
        method: 'get',
        url: '/api/gb_record/download/stop/' + this.deviceId + "/" + this.channelId+ "/" + this.stream
      }).then((res)=> {
        if (callback) callback(res)
      });*/
    },
    downloadFileClientEvent: function (){
      window.open(this.downloadFile )
    },
    getFileDownload: function (){
      const param = {
        mediaServerId:this.mediaServerId,
        app: this.app,
        stream: this.stream,
        startTime: null,
        endTime: null,
      }
      this.api.downloadTaskAdd(JSON.stringify(param)).then(res=>{
          apiResult(res.data,false,result=>{
            // 查询进度
            this.modal.title = this.$t('video_file_processing');
            this.taskId = res.data.data;
            this.percent = 0.0;
            this.getProgressForFileRun = true;
            this.getProgressForFileTimer();
          })
        /*if (res.data.code === 0 ) {
          // 查询进度
          this.modal.title = "录像文件处理中..."
          this.taskId = res.data.data;
          this.percent = 0.0;
          this.getProgressForFileRun = true;
          this.getProgressForFileTimer();
        }*/
      }).catch(function (error) {
        console.log(error);
      });

/*      this.$axios({
        method: 'get',
        url:`/record_proxy/${this.mediaServerId}/api/record/file/download/task/add`,
        params: {
          app: this.app,
          stream: this.stream,
          startTime: null,
          endTime: null,
        }
      }).then((res) =>{
        if (res.data.code === 0 ) {
          // 查询进度
          this.title = "录像文件处理中..."
          this.taskId = res.data.data;
          this.percentage = 0.0;
          this.getProgressForFileRun = true;
          this.getProgressForFileTimer();
        }
      }).catch(function (error) {
        console.log(error);
      });*/
    },
    getProgressForFileTimer: function (){
      if (!this.getProgressForFileRun || this.percent == 100) {
        return;
      }
      setTimeout( ()=>{
        if (!this.showDialog) return;
        this.getProgressForFile(this.getProgressForFileTimer)
      }, 1000)
    },


    getProgressForFile: function (callback){
      const param = {
        mediaServerId:this.mediaServerId,
        app: this.app,
        stream: this.stream,
        taskId: this.taskId,
        isEnd: true,
      }
      this.api.downloadTaskList(JSON.stringify(param)).then(res=>{
        console.log(res)
        apiResult(res.data,false,result=>{
          if (res.data.data.length === 0){
            this.percent = 0
            // 往往在多次请求后（实验五分钟的视频是三次请求），才会返回数据，第一次请求通常是返回空数组
            if (callback)callback()
            return
          }
          // res.data.data应是数组类型
          this.percent = parseFloat(res.data.data[0].percentage)*100
          if (res.data.data[0].percentage === '1') {
            this.getProgressForFileRun = false;
            this.downloadFile = res.data.data[0].downloadFile
            this.modal.title = this.$t('file_ready');
            // window.open(res.data.data[0].downloadFile)
          }else {
            if (callback)callback()
          }
        })
        /*if (res.data.code === 0) {
          if (res.data.data.length === 0){
            this.percent = 0
            // 往往在多次请求后（实验五分钟的视频是三次请求），才会返回数据，第一次请求通常是返回空数组
            if (callback)callback()
            return
          }
          // res.data.data应是数组类型
          this.percent = parseFloat(res.data.data[0].percentage)*100
          if (res.data.data[0].percentage === '1') {
            this.getProgressForFileRun = false;
            this.downloadFile = res.data.data[0].downloadFile
            this.modal.title = "文件处理完成，点击按扭下载"
            // window.open(res.data.data[0].downloadFile)
          }else {
            if (callback)callback()
          }
        }*/
      }).catch(function (error) {
        console.log(error);
      });
/*
      this.$axios({
        method: 'get',
        url:`/record_proxy/${this.mediaServerId}/api/record/file/download/task/list`,
        params: {
          app: this.app,
          stream: this.stream,
          taskId: this.taskId,
          isEnd: true,
        }
      }).then((res) => {
        console.log(res)
        if (res.data.code === 0) {
          if (res.data.data.length === 0){
            this.percentage = 0
            // 往往在多次请求后（实验五分钟的视频是三次请求），才会返回数据，第一次请求通常是返回空数组
            if (callback)callback()
            return
          }
          // res.data.data应是数组类型
          this.percentage = parseFloat(res.data.data[0].percentage)*100
          if (res.data.data[0].percentage === '1') {
            this.getProgressForFileRun = false;
            this.downloadFile = res.data.data[0].downloadFile
            this.title = "文件处理完成，点击按扭下载"
            // window.open(res.data.data[0].downloadFile)
          }else {
            if (callback)callback()
          }
        }
      }).catch(function (error) {
        console.log(error);
      });*/
    },
  },

  destroyed() {
    if (this.timer !== null) {
      window.clearTimeout(this.timer);
      this.timer = null;
    }
    window.removeEventListener('beforeunload', this.stopDownloadRecord)
  }
}
</script>
<style>

</style>
